<template>
  <el-button type="success" @click="showAddDialog">
    <el-icon>
      <Plus/>
    </el-icon>
    添加
  </el-button>
  <!--数据表格-->
  <el-table :data="list" height="400px" style="width: 100%;margin-top: 10px;margin-bottom: 10px" border>
    <el-table-column type="index" label="序号" width="180" :index="getIndex"></el-table-column>
    <el-table-column prop="tmName" label="品牌名称" width="180"></el-table-column>
    <el-table-column prop="logoUrl" label="品牌logo">
      <template v-slot="{row}">
        <img :src="row.logoUrl" style="height: 50px;width: 50px">
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template v-slot="{row}">
        <el-button type="warning" @click="showUpdateDialog(row)">
          <el-icon>
            <EditPen/>
          </el-icon>
          修改
        </el-button>
        <el-button type="danger" @click="deleteTrademark(row)">
          <el-icon>
            <Delete/>
          </el-icon>
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--分页器-->
  <el-pagination
      :page-size="this.limit"
      :page-sizes="[3, 5, 10]"
      background
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="this.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!--对话框-->
  <el-dialog v-model="dialogFormVisible" :title="tradeMarkFrom.id?'修改品牌':'添加品牌'" draggable>
    <el-form style="width: 80%" label-position="left" :model="tradeMarkFrom" :rules="rules" ref="ruleFrom">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="tradeMarkFrom.tmName" autocomplete="off"/>
        <!--        <img src="./src/assets/logo.png">-->
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <!--这里收集数据，不能使用v-model，因为不是表单数据-->
        <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
        >
          <img v-if="tradeMarkFrom.logoUrl" :src="tradeMarkFrom.logoUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
          <template #tip>
            <div>jpg/png files with a size less than 500KB.</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddOrUpdate"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {reqAddOrUpdateTradeMark, reqDeleteTradeMark, reqTrademarkList} from "../../api/realRequests";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: "TradewMark",
  data() {
    return {
      // 本地恶搞图片地址
      a: 'https://gss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=e0c7f85a3f87e9504242fb6a20087f7b/1e30e924b899a9011acfacaf18950a7b0308f5b5.jpg',
      // 当前第几页
      page: 1,
      // 每页条数
      limit: 10,
      // 数据总条数
      total: 0,
      // 列表展示的数据
      list: [],
      // 对话框打开状态
      dialogFormVisible: false,
      // 表单对象
      tradeMarkFrom: {
        tmName: '',
        logoUrl: ''
      },
      // 表单验证规则
      rules: {
        tmName: [
          // {required: true, message: '请输入品牌名称', trigger: 'blur'},
          // {min: 2, max: 100, message: '长度在2到100之间', trigger: 'change'},
          // 自定义规则方式如下：
          // {
          //   required: true,
          //   pattern: /(^((\+86)|(86))?(1[3-9])\d{9}$)|(^(0\d{2,3})-?(\d{7,8})$)/,
          //   message: '请输入正确的手机号',
          //   trigger: 'change'
          // },
        ],
        // logoUrl: [
        //   {
        //     required: true,
        //     message: '请选择品牌图片',
        //   },
        // ],
      }
    }
  },
  methods: {
    // 获取列表数据
    async getPageList() {
      const {page, limit} = this;
      let result = await reqTrademarkList(page, limit)
      console.log(5)
      if (result.code == 200) {
        this.list = result.data.records
        this.total = result.data.total
      }
    },
    // 计算并获取表格序号
    getIndex(index) {
      const page = this.page
      const limit = this.limit
      return (page - 1) * limit + index + 1
    },
    // 当前页码发生变化时触发，传递的形参是当前点击的页码
    handleCurrentChange(val) {
      this.page = val
      this.getPageList()
    },
    // 每页条数改变时
    handleSizeChange(val) {
      this.limit = val
      this.getPageList()
    },
    // 添加按钮
    showAddDialog() {
      // 打开对话框
      this.dialogFormVisible = true
      // 置空对话框
      this.tradeMarkFrom = {}
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      // res是图片上传成功后，服务器返回给前端的图片真实的网络地址，因为这张图片要存在某台服务器里
      console.log('上传成功', res, file)
      this.tradeMarkFrom.logoUrl = res.data
    },
    // 添加或者修改下的确定按钮
    async submitAddOrUpdate() {
      // this.$refs.ruleFrom.validate(async (success) => {
      //   if (success) {
      // 关闭对话框
      this.dialogFormVisible = false
      // 写着玩***************************************************************
      this.tradeMarkFrom.tmName = '人民万岁！！！'
      // 给图片添加本地恶搞图片地址
      this.tradeMarkFrom.logoUrl = this.a
      // 写着玩***************************************************************
      let result = await reqAddOrUpdateTradeMark(this.tradeMarkFrom)
      console.log(6)
      if (result.code == 200) {
        // 添加或者修改成功，弹出操作成功的提示
        ElMessage({message: this.tradeMarkFrom.id ? '修改成功！' : '添加成功！', type: 'success', duration: 2000})
        // 添加或者修改成功后，重新调用接口，查询品牌数据进行展示
        this.getPageList()
      }
      //   } else {
      //     // console.log('提交失败！')
      //     return false
      //   }
      // })
    },
    // 修改按钮
    showUpdateDialog(row) {
      this.dialogFormVisible = true
      // console.log(row)
      this.tradeMarkFrom = {...row}
    },
    // 删除按钮
    deleteTrademark(row) {
      // 确认提示框
      {
        ElMessageBox.confirm(
            `确定要删除${row.tmName}这个品牌吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error',
            }
        )
            // 点击确认时触发
            .then(async () => {
              // 发请求，删除
              let result = await reqDeleteTradeMark(row.id)
              // 删除成功
              if (result.code == 200) {
                // 弹窗
                ElMessage({
                  type: 'success',
                  message: '删除成功！',
                })
                // 再次查询数据，展示数据
                // 判断当前页删除完一条数据后是否还有数据，如果没有了，跳到上一页
                this.getPageList(this.list.length > 1 ? this.page : this.page - 1)
              }
            })
            // 点击取消时触发
            .catch(() => {
              ElMessage({
                type: 'info',
                message: 'Delete canceled',
              })
            })
      }
    }
  },

  mounted() {
    console.log(1)
    this.getPageList()//异步Ajax请求，结束会打印5
    this.submitAddOrUpdate()//异步Ajax请求，结束会打印6
    setTimeout(function () {
      console.log(2)
    }, 10)
    setTimeout(function () {
      console.log(4)
    }, 20)
    console.log(3)
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed red;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: red;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: red;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>